package com.irdstudio.apicenter.gateway.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import com.irdstudio.apicenter.gateway.comm.MaccsPacket;
import com.irdstudio.apicenter.gateway.comm.MaccsPacketUtil;
import com.irdstudio.apicenter.gateway.core.jdbc.MaccsBaseDAO;
import com.irdstudio.apicenter.gateway.util.spring.BeanUtils;
import com.irdstudio.apicenter.gateway.web.MaccsException;
import com.irdstudio.apicenter.gateway.web.MaccsTradeDefineVo;
import com.irdstudio.apicenter.gateway.web.view.JsonView;
import com.irdstudio.apicenter.gateway.web.view.View;

/**
 * 移动设备准入检查
 * @author zs.ligm
 * @version 1.0
 * @date 2015-07-24
 */
@Controller
public class AppEntryCheck implements IController{
	
	/* 文本日志输出 */
	private static final Logger logger = LoggerFactory
			.getLogger(AppEntryCheck.class);

	@Override
	public View execute(MaccsTradeDefineVo tradeDefine, MaccsPacket inPacket,
			HttpServletRequest request, HttpServletResponse response)
			throws MaccsException {

		// 接收移动客户端传过来的参数
		String appId = inPacket.getValue("appId");
		String deviceId = inPacket.getValue("d");

		// 判断是否传入必须的参数(移动设备号)
		logger.info("设备号:" + deviceId);
		if (StringUtils.isEmpty(deviceId)) {
			return new JsonView(request, response, MaccsPacketUtil
					.makeFailurePacket("未接收到移动设备号!"));
		}

		// 读取已登记设备列表,判断是否可以进入
		MaccsBaseDAO jdbcDao = BeanUtils.getBean(MaccsBaseDAO.class);
		String isAllow = jdbcDao
				.queryForObject(
						"select is_allow from app_device_register where app_id=? and device_id=?",
						new Object[] { appId, deviceId }, String.class);

		// 如果为空，说明还未登记，返回错误码及提示
		MaccsPacket outPacket = null;
		if (StringUtils.isEmpty(isAllow)) {
			outPacket = MaccsPacketUtil.makeCustomFailurePacket("900",
					"您的设备尚未登记!");
		} else if (isAllow.equals("N")) {
			// 如果标记为N，说明尚未允许进入应用
			outPacket = MaccsPacketUtil.makeCustomFailurePacket("901",
					"您的设备已登记,但尚未获准进入!");
		} else {
			outPacket = MaccsPacketUtil.makeSuccessPacket();
		}

		return new JsonView(request, response, outPacket);
	}

}
